package com.itlong.cloud.controller.huawei;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.operate.*;
import com.itlong.cloud.POJO.PO.AppPackagePO;
import com.itlong.cloud.POJO.PO.HuaweiOrderInfoPO;
import com.itlong.cloud.POJO.PO.PropertyPackagePO;
import com.itlong.cloud.POJO.VO.operate.OperateAppPackageGetPageVO;
import com.itlong.cloud.POJO.VO.operate.OperateProjectVO;
import com.itlong.cloud.POJO.VO.operate.OperatePropertyAccountVO;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.enumerate.HuaweiOrderTypeEnum;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.noncore.operate.IOperateAppPackageServiceClient;
import com.itlong.cloud.noncore.operate.IOperatePropertyPackageServiceClient;
import com.itlong.cloud.paymenthub.IPaymentTradeServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.user.operate.IOperatePropertyAccountServiceClient;
import com.itlong.cloud.utils.encrypt.DesEncryptUtil;
import com.itlong.cloud.utils.encrypt.HuaweiEncryptUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.random.LogicIdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by PPP on 2020/4/7.
 */
@RestController
@RequestMapping("/huawei/order")
public class StoreOrderController {

    private static Logger LOG = LoggerFactory.getLogger(StoreOrderController.class);

    private final String key = "908fc823-65e0-47e2-b520-18860e618e37";//华为key

    private final String packageName = "华为云市场用户套餐";//默认套餐名称

    private final String createProjectUrl = "http://www.itlongoa.com.cn:8099/api/project_info/save_project_info";//创建项目url

    private final String statusProjectUrl = "http://www.itlongoa.com.cn:8099/api/project_info/status";//心跳地址url

    private final String createProjectSecret = "B7F9F2D3E3D7A013";//创建项目key

    private final String phone = "18126126601";//运维电话

    private final String content = "旺龙创建项目服务异常无法与旺龙云服务通信,请查看";//短信内容

    @Autowired
    IOperatePropertyAccountServiceClient iOperatePropertyAccountServiceClient;

    @Autowired
    private IOperateAppPackageServiceClient iOperateAppPackageServiceClient;

    @Autowired
    private IPaymentTradeServiceClient iPaymentTradeServiceClient;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;


    /**
     * <desc>
     * <p>
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("/newInstance")
    @ResponseBody
    @UnAuthAccessRequired
    public Object valid(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> result = new HashMap<>();
        try {
            String mobilePhone = HuaweiEncryptUtil.decryptMobilePhoneOrEMail(key, request.getParameter("mobilePhone"), 128);
            String email = HuaweiEncryptUtil.decryptMobilePhoneOrEMail(key, request.getParameter("email"), 128);
            String customerName = request.getParameter("customerName");
            LOG.info("【SaaS下单入参】:" + String.format("activity:%s;businessId:%s;customerId:%s;customerName:%s;email:%s;expireTime:%s;" +
                            "mobilePhone:%s;orderId:%s;productId:%s;testFlag:%s;timeStamp:%s;userId:%s;userName:%s;authToken:%s", request.getParameter("activity"), request.getParameter("businessId")
                    , request.getParameter("customerId"), customerName, email, request.getParameter("expireTime"), mobilePhone, request.getParameter("orderId")
                    , request.getParameter("productId"), request.getParameter("testFlag"), request.getParameter("timeStamp"), request.getParameter("userId"), request.getParameter("userName"), request.getParameter("authToken")));
            //保存数据
            HuaweiOrderInfoPO po = new HuaweiOrderInfoPO();
            po.setActivity(request.getParameter("activity"));
            po.setBusinessId(request.getParameter("businessId"));
            po.setCustomerId(request.getParameter("customerId"));
            po.setCustomerName(customerName);
            po.setEmail(email);
            po.setExpireTime(request.getParameter("expireTime"));
            po.setMobilePhone(mobilePhone);
            po.setOrderId(request.getParameter("orderId"));
            po.setProductId(request.getParameter("productId"));
            po.setTestFlag(request.getParameter("testFlag"));
            po.setTimeStamp(request.getParameter("timeStamp"));
            po.setUserId(request.getParameter("userId"));
            po.setUserName(request.getParameter("userName"));
            po.setAuthToken(request.getParameter("authToken"));
            po.setStatus(1);
            po.setCreateTime(new Date());
            po.setOrderType(HuaweiOrderTypeEnum.MANAGE.getType());
            iPaymentTradeServiceClient.saveHuaweiSaaSData(po);
            //创建项目
            if (customerName == null && "".equals(customerName)) {//为空则使用默认项目+10位客户编号
                customerName = "新建项目" + request.getParameter("customerId").substring(0, 10);
            }
            OperateProjectGetPageDTO projectPageDTO = new OperateProjectGetPageDTO();
            projectPageDTO.setProjectName(customerName);
            List<OperateProjectVO> projectList = iOperateProjectServiceClient.getPage(projectPageDTO).getRows();
            String projectId = "";
            String userName = "";
            if (projectList == null || projectList.size() == 0) {
                //请求一卡通新建项目
              /*   SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = new Date();
                String createTime = df.format(date);//签名用时间
               String encryptScript = takeInputPama(createTime, createProjectSecret, customerName);//入参处理
                String jsonStr;*/
                try {
                    //jsonStr = HttpProtocolUtil.doGet(createProjectUrl + "?encryptScript=" + encryptScript.replaceAll("\\+", "%2B"), null);

                    OperateProjectSaveDTO projectSaveDTO = new OperateProjectSaveDTO();
                    projectSaveDTO.setProductType(1);
                    projectSaveDTO.setProjectProperty(0);
                    projectSaveDTO.setProjectName(customerName);
                    projectSaveDTO.setLoginUserId(po.getUserId());
                    Integer integer = iOperateProjectServiceClient.saveProject(projectSaveDTO);
                    projectId = projectSaveDTO.getProjectId();
                    if (integer == null) {
                        LOG.info("创建项目失败！");
                        iIotTpSmsServiceClient.sendSmsCodeByPhone(phone, content);
                    }
                } catch (Exception e) {
                    LOG.info("创建项目服务异常");
                    iIotTpSmsServiceClient.sendSmsCodeByPhone(phone, content);
                    return null;
                }
              /*  jsonStr = DesEncryptUtil.aesDecrypt(jsonStr,createProjectSecret);
                LOG.info("创建项目返回值:" + jsonStr);
                JSONObject json = (JSONObject) JSONObject.parse(jsonStr);
                if (json.get("code").toString().equals("0")) {
                    JSONObject data = (JSONObject) JSONObject.parse(json.get("data").toString());
                    projectId = data.get("projectId").toString();
                }*/
            } else {
                projectId = projectList.get(0).getProjectId();
            }
            if (!"".equals(projectId)) {//项目创建成功的情况下
                //查询是否有物业账号有则直接返回
                OperatePropertyAccountGetPageDTO propertyPageDTO = new OperatePropertyAccountGetPageDTO();
                propertyPageDTO.setProjectName(customerName);
                propertyPageDTO.setProjectId(projectId);
                List<OperatePropertyAccountVO> listPropertyAccount = iOperatePropertyAccountServiceClient.getPage(propertyPageDTO).getRows();
                if (listPropertyAccount != null && listPropertyAccount.size() > 0) {//有此物业账号直接返回
                    userName = listPropertyAccount.get(0).getUserName();
                } else {//无此物业账号创建并绑定套餐
                    //创建物业账号
                    OperatePropertyAccountSaveDTO saveDTO = new OperatePropertyAccountSaveDTO();
                    saveDTO.setProjectIds(projectId);//管辖项目id，多个以英文逗号分隔
                    saveDTO.setRoleId("5");//角色类型ID
                    userName = "ITL" + projectId;
                    saveDTO.setUserName(userName);//管理员账号
                    saveDTO.setPropertyName(customerName);//物业名称
                    saveDTO.setDescription("");//备注
                    saveDTO.setStatus(1);//账号状态：1-正常，2-禁用
                    String userId = iOperatePropertyAccountServiceClient.savePropertyAccountSaas(saveDTO);//创建物业账号拿到账号编号

//                    //使用套餐进行授权
                    OperateAppPackageGetPageDTO operateAppPackageGetPageDTO = new OperateAppPackageGetPageDTO();
                    operateAppPackageGetPageDTO.setAppPackageName(packageName);
                    List<OperateAppPackageGetPageVO> packageList = iOperateAppPackageServiceClient.getPage(operateAppPackageGetPageDTO).getRows();
                    if (packageList.size() > 0) {
                        //物业管理员赋值套餐
                        iOperateAppPackageServiceClient.allotPackageProject(packageList.get(0).getAppPackageId(), projectId, projectId);
                    }
                }
            }

            result.put("resultCode", "000000");
            result.put("resultMsg", "success");
            result.put("instanceId", LogicIdUtil.bussinessId());
            result.put("encryptType", "2");
            Map<String, Object> appInfo = new HashMap<>();
            appInfo.put("frontEndUrl", "https://property.jia-r.com");
            appInfo.put("adminUrl", "https://property.jia-r.com");
            LOG.info("物业账号userName:" + userName);
            appInfo.put("userName", HuaweiEncryptUtil.generateSaaSUsernameOrPwd(key, userName, 128));
            appInfo.put("password", HuaweiEncryptUtil.generateSaaSUsernameOrPwd(key, "itlong@111", 128));
            result.put("appInfo", appInfo);
            response.addHeader("sign_type", "\"HMAC-SHA256\"");
            response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + ",signature=\"" + HuaweiEncryptUtil.base_64(HuaweiEncryptUtil.hmacSHA256("908fc823-65e0-47e2-b520-18860e618e37", JsonUtil.toJSON(result))) + "\"");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * <desc>
     * <p>
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("/newInstanceCount")
    @ResponseBody
    @UnAuthAccessRequired
    public Object newInstanceCount(HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "000000");
        result.put("resultMsg", "success");
        result.put("instanceId", LogicIdUtil.bussinessId());
        result.put("encrtptType", "1");
        Map<String, Object> appInfo = new HashMap<>();
        appInfo.put("frontEndUrl", "xxx");
        appInfo.put("adminUrl", "xxx");
        appInfo.put("userName", HuaweiEncryptUtil.encryptAESCBCEncode("xxxxxxxxsxxxxxxxxxxxx", "908fc823-65e0-47e2-b520-18860e618e37", "", 128));
        appInfo.put("password", HuaweiEncryptUtil.encryptAESCBCEncode("xxxxxxxxsxxxxxxxxxxxx", "908fc823-65e0-47e2-b520-18860e618e37", "", 128));
        result.put("appInfo", appInfo);
        response.addHeader("sign_type", "\"HMAC-SHA256\"");
        response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + ",signature=\"" + HuaweiEncryptUtil.base_64(HuaweiEncryptUtil.hmacSHA256("908fc823-65e0-47e2-b520-18860e618e37", JsonUtil.toJSON(result))) + "\"");
        return result;
    }

    /**
     * <desc>
     * <p>
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("/refreshInstance")
    @ResponseBody
    @UnAuthAccessRequired
    public Object valid2(HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "000000");
        result.put("resultMsg", "success");
        response.addHeader("sign_type", "\"HMAC-SHA256\"");
        response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + ",signature=\"" + HuaweiEncryptUtil.base_64(HuaweiEncryptUtil.hmacSHA256("908fc823-65e0-47e2-b520-18860e618e37", JsonUtil.toJSON(result))) + "\"");
        return result;
    }

    /**
     * <desc>
     * <p>
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("/expireInstance")
    @ResponseBody
    @UnAuthAccessRequired
    public Object valid3(HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "000000");
        result.put("resultMsg", "success");
        response.addHeader("sign_type", "\"HMAC-SHA256\"");
        response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + ",signature=\"" + HuaweiEncryptUtil.base_64(HuaweiEncryptUtil.hmacSHA256("908fc823-65e0-47e2-b520-18860e618e37", JsonUtil.toJSON(result))) + "\"");
        return result;
    }

    /**
     * <desc>
     * <p>
     * </desc>
     *
     * @param request
     * @return
     * @author Jiaqi.X
     * @createDate 2020/04/07
     */
    @RequestMapping("/releaseInstance")
    @ResponseBody
    @UnAuthAccessRequired
    public Object valid4(HttpServletRequest request, HttpServletResponse response) throws IOException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, NoSuchPaddingException {
        Map<String, Object> result = new HashMap<>();
        result.put("resultCode", "000000");
        result.put("resultMsg", "success");
        response.addHeader("sign_type", "\"HMAC-SHA256\"");
        response.addHeader("Body-Sign", "sign_type=\"HMAC-SHA256\"" + ",signature=\"" + HuaweiEncryptUtil.base_64(HuaweiEncryptUtil.hmacSHA256("908fc823-65e0-47e2-b520-18860e618e37", JsonUtil.toJSON(result))) + "\"");
        return result;
    }

    /**
     * <desc>
     * 获取加密入参
     * <desc/>
     *
     * @param createTime 创建时间
     * @param appsecret  开发者密码
     * @return 加密字符串
     * @author ITLONG
     * @createDate 2019/01/15
     */
    public String takeInputPama(String createTime, String appsecret, String projectName) throws Exception {
        JSONObject json = new JSONObject();
        json.put("projectName", projectName);
        Map<String, Object> jsonToMap = JsonToMap(json.toJSONString());//将json转换为map
        String sign = Md5EncryptUtil.cloudDeviceMd5(jsonToMap, createTime, appsecret);//签名运算
        //加密前先将createTime传入加密方法,最后在将createTime和sign放入json中
        json.put("createTime", createTime);
        json.put("appSecret", appsecret);
        json.put("sign", sign);
        String encryptResult = DesEncryptUtil.aesEncryptSDK(json.toJSONString(), appsecret).replaceAll("//+", "%2B");//使用key进行aes加密运算
        return encryptResult;
    }

    /**
     * json转map
     *
     * @param json
     * @return map
     */
    public static Map<String, Object> JsonToMap(String json) {
        Map<String, Object> map = new HashMap<>();
        if (json != null) {
            map = (Map) JSON.parse(json);
        }
        return map;
    }
}